const Router = require('koa-router')
const address = new Router()
//！拿到前端的数据
//数据库连接池
const pg = require('pg');
let psql = new pg.Pool({
  database: 'running',
  user: 'run',
  port: 5432,
  host: '82.157.94.115',
  password: 'z12345678',
  max: 2
})
function makeId() {
  let id = Math.random().toString(16).substring(2);
  let id2 = Math.random().toString(16).substring(2);
  return (id + id2).substring(0, 12);
}
address.post('/address', async ctx => {
  let { region, name, tel, door } = ctx.request.body;
  console.log("region", region);
  console.log("name", name);
  console.log("tel", tel);
  console.log("door", door);

  let insertContentPostgresql = `insert into address (region,name,tel,door) values ('${region}','${name}','${tel}','${door}')`;
  let content = await psql.query(insertContentPostgresql);

  if (content.rowCount > 0)
    ctx.body = {
      region: region,
      name: name,
      tel: tel,
      door: door
    };


})
address.get('/address1', async ctx => {
  let searchContentPostgresql = `select * from address`;
  let content = await psql.query(searchContentPostgresql);
  // console.log(content)
  // console.log("行数", content.rowCount)

  if (content.rowCount > 0) {
    var addressObj = [];
    for (var i = 0; i < content.rowCount; i++) {
      var obj = {
        region: content.rows[i].region,
        name: content.rows[i].name,
        tel: content.rows[i].tel,
        door: content.rows[i].door
      }

      addressObj.push(obj);
    }

    ctx.body = {
      addressObj
    };
  }
})
module.exports = address